<template>
    <div>
        <KnHeader></KnHeader>
        <el-row>
            <el-col :span="4">
                <div class="grid-content bg-purple">
                    <el-tree :data="docsTree" :props="defaultProps" @node-click="handleNodeClick"
                        :default-expand-all="true"></el-tree>
                </div>
            </el-col>
            <el-col :span="20">
                <el-row>
                    <el-col :span="16">
                        <el-button type="primary" @click="openModel">新增</el-button>
                    </el-col>
                    <el-col :span="4">
                        <el-input v-model="search" placeholder="请输入内容"></el-input>
                    </el-col>
                    <el-col :span="1" :offset="1">
                        <el-button type="primary" icon="el-icon-search">搜索</el-button>
                    </el-col>
                </el-row>
                <div class="grid-content bg-purple">
                    <el-table :data="docsTree" style="width: 100%;margin-bottom: 20px;" row-key="id" border
                        default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                        <el-table-column prop="name" label="名称" sortable width="180">
                        </el-table-column>
                        <!-- 操作列（编辑、修改、删除） -->
                        <el-table-column label="操作" width="180">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="previewDoc(scope.row)">
                                    文档预览
                                </el-button>
                                <el-button type="text" size="small" @click="handleModify(scope.row)">
                                    编辑
                                </el-button>

                                <el-button type="text" size="small" @click="handleDelete(scope.row)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-col>
        </el-row>
        <el-dialog title="章节内容" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
            <el-form ref="form" v-model="form" label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <!-- 父文档字段（树形选择器） -->
                <el-form-item label="父文档">
                    <el-tree ref="tree" :data="docsTree" node-key="id" :props="defaultProps" :default-expand-all="false"
                        node-class-name="custom-tree-node"
                        @node-click="handleCheckChange">
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                            <span>{{ node.label }}</span>
                            <!-- 可在此添加更多自定义内容 -->
                        </span>
                    </el-tree>
                </el-form-item>
                <el-form-item label="内容">
                    <div class="editor-container">
                        <rich-text-editor v-model="form.text" class="scrollable-editor"></rich-text-editor>
                    </div>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model.number="form.sort"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 抽屉 -->
        <el-drawer title="我是标题" :visible.sync="drawer" :with-header="false">
            <div v-html="plainText" class="richText-preview"></div>
        </el-drawer>

    </div>
</template>

<script>
import { getDocTree } from '@/apis/docApi.js';
import KnHeader from '@/components/KnHeader.vue';
import RichTextEditor from '@/components/RichTextEditor.vue';
import { saveDocAndContent, getDocAndContentById, deleteDocAndContentById } from '@/apis/docApi.js'
import { getContentById, updateDocAndContentById } from '@/apis/contentApi.js'
export default {
    //import引入组件才能使用
    components: {
        KnHeader,
        RichTextEditor
    },
    props: {},
    data() {
        return {
            ebookId: this.$route.params.id,// 接收路径参数 id
            docsTree: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            tableData: [],
            dialogVisible: false,
            form: {},
            search: '',
            drawer: false,
            plainText: '',
            visible: false,
        };
    },
    // 计算属性
    computed: {},
    // 方法集合
    methods: {
        // 递归为所有节点添加 disabled 属性
        addDisabledProperty(nodes) {
            nodes.forEach(node => {
                node.disabled = false; // 初始为未禁用
                if (node.children) {
                    this.addDisabledProperty(node.children);
                }
            });
        },
        // 递归查找并禁用指定节点及其子节点
        disableNodeAndChildren(nodes, parentId) {
            nodes.forEach(node => {
                if (node.id === parentId) {
                    node.disabled = true;
                }
                if (node.children) {
                    this.disableNodeAndChildren(node.children, parentId);
                }
            });
        },
        // 加载树数据时调用
        async getDocTreeVue() {
            let res = await getDocTree(this.ebookId);
            console.log(res);
            this.docsTree = res.data.data;
            this.addDisabledProperty(this.docsTree); // 添加 disabled 属性
        },
        handleNodeClick(data) {
            console.log(data);
            this.form.parent = data.id
        },
        async getDocTreeVue() {
            let res = await getDocTree(this.ebookId)
            console.log(res);
            this.docsTree = res.data.data
        },
        cancel() {
            this.dialogVisible = false
            this.form = {}
        },
        async save() {
            this.form.ebookId = this.ebookId
            if (this.form.id) {
                console.log("ebookOperatorVue    162====>",this.form);
                let res = await updateDocAndContentById(this.form)
                console.log("ebookOperatorVue 163", res);
                if (res.data.status === 200) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    })
                }else{
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    })
                }

            } else {
                console.log(this.form);
                let res = await saveDocAndContent(this.form)
                if (res.data.status === 200) {
                    this.$message('保存成功', 'success')
                }
            }

            this.form = {}
            this.dialogVisible = false
            this.getDocTreeVue()
        },
        openModel() {
            this.dialogVisible = true
        },
        handleCheckChange(data, checked, indeterminate) {
            console.log('123123');

            if (checked) {
                this.form.parent = data.id; // 当节点被选中时，设置 form.parent 为选中节点的 id
            } else {
                this.form.parent = null; // 当节点被取消选中时，清空 form.parent
            }
            console.log('选中的父文档ID:', this.form.parent);
        },
        async previewDoc(row) {
            console.log('row', row);
            let res = await getContentById(row.id)
            console.log(res);

            this.plainText = res.data.data.content
            this.drawer = true
        },
        // 编辑方法
        async handleModify(row) {
            console.log('编辑行数据:', row);
            try {
                let res = await getDocAndContentById(row.id);
                console.log("响应数据:", res);
                this.form = res.data.data;

                // 禁用当前节点及其子节点
                this.disableNodeAndChildren(this.docsTree, this.form.id);

                this.dialogVisible = true;

                this.$nextTick(() => {
                    // 设置选中的节点
                    if (this.form.parent) {
                        const tree = this.$refs.tree;
                        if (tree) {
                            // 展开所有父节点
                            this.expandParentNodes(tree, this.form.parent);

                            // 设置当前选中节点
                            tree.setCurrentKey(this.form.parent);
                        }
                    }
                });
            } catch (error) {
                console.error('获取文档详情失败:', error);
            }
        },

        // 递归展开所有父节点
        expandParentNodes(tree, parentId) {
            const expand = (nodes) => {
                for (let node of nodes) {
                    if (node.id === parentId) {
                        node.expanded = true;
                        return true;
                    }
                    if (node.children) {
                        if (expand(node.children)) {
                            node.expanded = true;
                            return true;
                        }
                    }
                }
                return false;
            };
            expand(tree.store.nodesMap ? Object.values(tree.store.nodesMap) : []);
        },

        // 关闭编辑对话框时恢复节点状态
        closeDialog() {
            this.dialogVisible = false;
            this.restoreDisabledProperty(this.docsTree);
            this.form = {};
        },

        // 递归恢复所有节点的 disabled 属性
        restoreDisabledProperty(nodes) {
            nodes.forEach(node => {
                node.disabled = false;
                if (node.children) {
                    this.restoreDisabledProperty(node.children);
                }
            });
        },

        // 在组件销毁前恢复节点状态（可选）
        beforeDestroy() {
            this.restoreDisabledProperty(this.docsTree);
        },

        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
            this.form = {}
        },
        async handleDelete(row) {
            console.log(row);
            const deleteDocAndContentPo = {
                id: row.id,
                ebookId: this.ebookId
            }
            let res = await deleteDocAndContentById(deleteDocAndContentPo)
            console.log(res);
            if (res.data.status === 200) {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                })
            }
            this.getDocTreeVue()
        }
    },
    created() {
        this.getDocTreeVue()
    }
}
</script>

<style scoped>
.scrollable-editor {
    max-height: 400px;
    /* 设置最大高度 */
    overflow-y: auto;
    /* 当内容超出时显示滚动条 */
    border: 1px solid #eee;
    /* 可选：添加边框 */
    padding: 10px;
    /* 可选：添加内边距 */
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.richText-preview {
    border: 1px solid #ccc;
    padding: 10px;
    margin-top: 10px;
}
</style>